const query = require('../db/mysql')
const {success, error} = require('../model/model')
const {md5} = require('utility')
const jwt = require('jsonwebtoken')
class ListController {
    register=async(ctx) => {
        //如何实现注册功能
        const {username,password,nickname} = ctx.request.body;
        // 判断账号是否已经存在
        const isHaveSql = `select * from users where username="${username}"`
        const isHave = await query(isHaveSql)
        if(isHave.length){
            ctx.body = error('账号已存在')
            return;
        }
        const sql = `insert into users(username,password,nickname) values("${username}","${md5(String(password))}","${nickname}")`
        const data = await query(sql)
        if(data.affectedRows === 1) {
            ctx.body = success('注册成功');
        } else {
            ctx.body = error('注册失败');
        }
    }
    login = async(ctx) =>{
        const {username, password} = ctx.request.body;
        const sql = `select id,username,nickname from users where username="${username}" and password="${md5(String(password))}"`
        console.log(sql)
        const data = await query(sql);
        if(data.length){
            ctx.body = success({
                data: data[0],
                token: jwt.sign({id:data[0].id,username: data[0].username}, '1812a')
            })
        } else {
            ctx.body = error("请检查账号密码")
        }
    }
}

module.exports = new ListController()